package com.example.dayday.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dayday.common.BaseContext;
import com.example.dayday.common.R;
import com.example.dayday.common.ResponseEnum;
import com.example.dayday.exception.BusinessException;
import com.example.dayday.pojo.Student;
import com.example.dayday.pojo.Teacher;
import com.example.dayday.service.StudentService;
import com.example.dayday.service.TeacherService;
import com.example.dayday.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Api(tags = "用户登录")
@RequestMapping("/user")
@RestController
@CrossOrigin
@Slf4j
public class LoginController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public R login(@RequestBody LoginVO loginForm, HttpSession session){
        try {
            if(loginForm.getRole() == 1){
                LambdaQueryWrapper<Student> qw = new LambdaQueryWrapper<>();
                qw.eq(Student::getStudentId, loginForm.getId());
                qw.eq(Student::getPassword, loginForm.getPassword());
                Student student = studentService.getOne(qw);
                if(student != null){
                    student.setRole(1);
                    student.setUserId(student.getStudentId());
                    session.setAttribute("user",student);
                    return R.ok().data("user",student);
                }
            }else if(loginForm.getRole() == 2){
                LambdaQueryWrapper<Teacher> qw = new LambdaQueryWrapper<>();
                qw.eq(Teacher::getTeacherId,loginForm.getId());
                qw.eq(Teacher::getPassword, loginForm.getPassword());
                Teacher teacher = teacherService.getOne(qw);
                if(teacher != null){
                    teacher.setRole(2);
                    teacher.setUserId(teacher.getTeacherId());
                    session.setAttribute("user",teacher);
                    return R.ok().data("user",teacher);
                }

            }
            return R.error().message("账号未注册！");
        }catch (Exception e){
            throw new BusinessException(ResponseEnum.LOGINERROR,e);
        }
    }


    @GetMapping("/info")
    public R date(HttpSession session){
        Object user = session.getAttribute("user");
        return R.ok().data("user",user);
    }

    @GetMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate(); //清除
        BaseContext.removeId();
        return R.ok();
    }
}
